<template>
    <el-form-item label="&选择客户" prop="customerId">
      <el-select 
        v-model="form.customerId" 
        filterable
        remote 
        reserve-keyword
        placeholder="请输入公司名"
        :remote-method="searchCustomersByCompany"
        :loading="customerLoading"
        style="width: 40%"
        @change="handleCustomerSelect"
        
      >
        <el-option
          v-for="customer in customerOptions"
          :key="customer.cid" 
          :label="`${customer.name}  (ID: ${customer.cid})`" 
          :value="customer.cid" 
        >
          <div class="customer-option">
            <span class="customer-id">ID: {{ customer.cid  }}</span>
            <span class="customer-name">{{ customer.name  }}</span>
            <span class="customer-company" v-if="customer.company"> 
              ({{ customer.company  }})
            </span>
          </div>
        </el-option>
      </el-select>
    </el-form-item>
  </template>
   
  <script setup>
  import { ref } from 'vue'
  import { customer_ListWithFiltersAPI } from '@/api/api'
  import { ElMessage } from 'element-plus'
   
  const props = defineProps({
    modelValue: [String, Number]  // 接收v-model绑定的customerId
  })
   
  const emit = defineEmits(['update:modelValue', 'select'])
   
  // 数据状态 
  const form = ref({
    customerId: props.modelValue  
  })
  const customerOptions = ref([])
  const customerLoading = ref(false)
  const searchTimer = ref(null)
   
  // 根据姓名搜索客户
  const searchCustomersByCompany = (query) => {
    if (!query || query.trim()  === '') {
      customerOptions.value  = []
      return
    }
   
    clearTimeout(searchTimer.value) 
    customerLoading.value  = true
    
    searchTimer.value  = setTimeout(async () => {
      try {
        const res = await customer_ListWithFiltersAPI({
          company: query.trim(), 
          limit: 10 
        })
        
        if (res.data?.data?.length)  {
          customerOptions.value  = res.data.data.map(item  => ({
            cid: item.cid, 
            name: item.name  || '未命名客户',
            company: item.company, 
            phone: item.phone 
          }))
        } else {
          customerOptions.value  = []
          ElMessage.warning(' 未找到匹配客户')
        }
      } catch (error) {
        console.error(' 客户搜索失败:', error)
        ElMessage.error(' 客户搜索失败')
      } finally {
        customerLoading.value  = false 
      }
    }, 500) // 500ms防抖
  }
   
  // 客户选择处理 
  const handleCustomerSelect = (customerId) => {
    emit('update:modelValue', customerId)
    
    const selectedCustomer = customerOptions.value.find( 
      item => item.cid  === customerId
    )
    if (selectedCustomer) {
      emit('select', selectedCustomer)
    }
  }
   
  // 清空选择 
  const clearSelection = () => {
    form.value.customerId  = null
    customerOptions.value  = []
  }
  </script>
   
  <style scoped>
  .customer-option {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .customer-id {
    color: #909399;
    font-size: 12px;
    min-width: 60px;
  }
  .customer-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .customer-company {
    color: #67c23a;
    font-size: 12px;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  </style>